package org.jsbd.boss.util;

import java.net.Inet4Address;

/**
 * @desc
 * @Date 2018/8/8 18:51
 * @Author xupengcheng [xupengcheng@zhexinit.com]
 */
public class IpUtil {

    public static Long ipToLong(String strIp) {
        String[] ip = strIp.split("\\.");
        return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
    }


    public static int inetAddressToInt(Inet4Address inetAddr) throws IllegalArgumentException {
        byte[] addr = inetAddr.getAddress();
        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
    }

    public static int inetAddressToInt(String ip) {
        try {
            Inet4Address address = (Inet4Address) Inet4Address.getByName(ip);
            byte[] addr = address.getAddress();
            return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }


    public static void main(String[] args) {
        System.out.println(inetAddressToInt("115.192.189.170"));
    }
}
